package com.xqb.listen.ui.music

import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ChainStyle
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.xqb.listen.R
import com.xqb.listen.manager.media.model.MediaModel
import com.xqb.listen.manager.permission.PermissionUtil
import com.xqb.listen.manager.permission.model.MediaType
import com.xqb.listen.navigation.NavParams
import com.xqb.listen.ui.music.mvi.LocalMusicIntent
import com.xqb.listen.ui.music.mvi.LocalMusicViewModel
import com.xqb.listen.ui.theme.BtnBlue
import com.xqb.listen.ui.theme.White
import com.xqb.listen.ui.theme.White50
import com.xqb.listen.ui.theme.White80
import com.xqb.listen.ui.widegts.PageToolbar

/**
 * @author Ling
 * @date :2024/11/14 16:18
 */

@Composable
fun LocalMusicPage(onSkipPage : (navParams: NavParams)-> Unit)
{

    val vm = viewModel(LocalMusicViewModel::class)
    val uiState = vm.uiState.collectAsStateWithLifecycle()
    val context = LocalView.current.context


    val permissionLaunch = if(!uiState.value.hasPermission)
    {
        rememberLauncherForActivityResult(contract = ActivityResultContracts.RequestPermission())
        {
            if(it) vm.sendUiIntent(LocalMusicIntent.GetLocalMusic)
        }
    }
    else null



    Column(Modifier
        .fillMaxSize()
        .systemBarsPadding()
    ) {
        PageToolbar(
            title = "本地音乐",
            modifier = Modifier
                .height(52.dp)
        ) {
            onSkipPage(NavParams(NavParams.Router.EXIT))
        }
        if(!uiState.value.hasPermission) {
            Spacer(modifier = Modifier.weight(0.6f))
            Image(
                painter = painterResource(id = R.drawable.img_empty),
                contentDescription = null,
                modifier = Modifier
                    .align(Alignment.CenterHorizontally)
            )
            Spacer(modifier = Modifier.height(20.dp))
            Box(
                contentAlignment = Alignment.Center,
                modifier = Modifier
                    .width(182.dp)
                    .height(40.dp)
                    .background(
                        BtnBlue,
                        RoundedCornerShape(10.dp)
                    )
                    .clip(RoundedCornerShape(10.dp))
                    .clickable {
                        PermissionUtil
                            .getMediaPermission(context, MediaType.AUDIO)
                            ?.let {
                                permissionLaunch?.launch(it)
                            }
                    }
                    .align(Alignment.CenterHorizontally)
            ) {
                Text(text = "获取权限" , color = White , fontWeight = FontWeight.Bold)
            }
            Spacer(modifier = Modifier.weight(1.4f))
        }
        else {
            LaunchedEffect(Unit) {
                vm.sendUiIntent(LocalMusicIntent.GetLocalMusic)
            }
            if(uiState.value.audioList.isEmpty()){
                Spacer(modifier = Modifier.weight(0.6f))
                Image(
                    painter = painterResource(id = R.drawable.img_empty),
                    contentDescription = null,
                    modifier = Modifier
                        .align(Alignment.CenterHorizontally)
                )
                Spacer(modifier = Modifier.height(20.dp))
                Text(
                    text = "没有找到音频文件" ,
                    color = White80,
                    fontSize = 13.sp,
                    modifier = Modifier
                        .align(Alignment.CenterHorizontally)
                )
                Spacer(modifier = Modifier.weight(1.4f))
            }else{
                LazyColumn(modifier = Modifier
                    .fillMaxSize()
                ) {
                    items(uiState.value.audioList){
                        MusicListItem(
                            item = it,
                            onItemClick = {
                                vm.sendUiIntent(LocalMusicIntent.PlayMusic(it))
                            },
                            onItemChildClick = {

                            }
                        )
                    }
                }
            }
        }
    }
}

//音乐列表Item
@Composable
fun MusicListItem(
    item : MediaModel,
    modifier: Modifier = Modifier,
    onItemClick : (() -> Unit)? = null,
    onItemChildClick : (() -> Unit)? = null,
){
    ConstraintLayout(modifier = modifier
        .height(54.dp)
        .fillMaxWidth()
        .clickable {
            onItemClick?.let { it() }
        }
    ) {
        val (title , author , more) = createRefs()
        Text(
            text = item.filename,
            color = White,
            fontWeight = FontWeight.Medium,
            fontSize = 14.sp,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
            modifier = Modifier
                .padding(start = 15.dp)
                .constrainAs(title) {
                    width = Dimension.fillToConstraints
                    start.linkTo(parent.start)
                    top.linkTo(parent.top)
                    end.linkTo(more.start)
                    bottom.linkTo(author.top)
                }
        )
        Text(
            text = item.author ?: "未知",
            color = White50,
            fontSize = 12.sp,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
            modifier = Modifier
                .padding(start = 15.dp)
                .constrainAs(author) {
                    width = Dimension.fillToConstraints
                    top.linkTo(title.bottom)
                    start.linkTo(parent.start)
                    end.linkTo(title.end)
                    bottom.linkTo(parent.bottom)
                }
        )
        createVerticalChain(elements = arrayOf(title , author) , chainStyle = ChainStyle.Packed)
        Icon(
            painter = painterResource(id = R.drawable.ic_more_setting),
            contentDescription = null,
            tint = White,
            modifier = Modifier
                .padding(end = 10.dp)
                .size(30.dp)
                .clip(CircleShape)
                .constrainAs(more) {
                    end.linkTo(parent.end)
                    top.linkTo(parent.top)
                    bottom.linkTo(parent.bottom)
                }
                .clickable {
                    onItemChildClick?.let { it() }
                }
        )
    }
}

@Preview(showBackground = true , showSystemUi = true)
@Composable
fun LocalMusicPreview(){
    LocalMusicPage{}
}